#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "global.h"
#include <QRegularExpression>
#include "httpmgr.h"
#include <QJsonDocument>
#include <QJsonObject>

RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
    , countdown_(COUNT_DOWN)
{
    ui->setupUi(this);

    initHttpHandlers();


    ui->pass_edit->setEchoMode(QLineEdit::Password);
    ui->confirm_edit->setEchoMode(QLineEdit::Password);
    //初始化把state属性设置为normal状态
    ui->err_tip->setProperty("state","normal");
    repolish(ui->err_tip);


    ui->pass_visible->SetState("unvisible","unvisible_hover","unvisible_press",
                                "visible","visible_hover","visible_press");
    ui->confirm_visible->SetState("unvisible","unvisible_hover","unvisible_press",
                               "visible","visible_hover","visible_press");

    //连接ClickedLabel对象的信号和槽
    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        //改变该label对应的密码文本框的状态
        auto state = ui->pass_visible->GetCurState();
        if(state==ClickLbState::Normal)
        {
            ui->pass_edit->setEchoMode(QLineEdit::Password);
        }
        else
        {
            ui->pass_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";

    });
    connect(ui->confirm_visible,&ClickedLabel::clicked,this,[this](){
        auto state = ui->confirm_visible->GetCurState();
        if(state==ClickLbState::Normal)
        {
            ui->confirm_edit->setEchoMode(QLineEdit::Password);
        }
        else
        {
            ui->confirm_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    countdown_timer_ = new QTimer(this);
    connect(countdown_timer_,&QTimer::timeout,this,[this](){
        countdown_--;
        if(countdown_==0)
        {
            countdown_timer_->stop();
            countdown_=COUNT_DOWN;
            //发送一个 切换界面的信号
            emit sigSwitchLogin();
            return;
        }
        QString str = QString("注册成功，%1 s后返回登陆").arg(countdown_);
        ui->tip_lb->setText(str);
    });


    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reg_mod_finish,this,&RegisterDialog::slot_reg_mod_finish);
    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkUserValid();
    });
    connect(ui->email_edit,&QLineEdit::editingFinished,this,[this](){
        checkEmailValid();
    });
    connect(ui->pass_edit,&QLineEdit::editingFinished,this,[this](){
        checkPassValid();
    });

    connect(ui->confirm_edit,&QLineEdit::editingFinished,this,[this](){
        checkConfirmValid();
    });
    connect(ui->verify_edit,&QLineEdit::editingFinished,this,[this](){
        checkVerifyValid();
    });


}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::on_get_code_clicked()
{
    //获取邮箱地址验证
    QString email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool isMatch = regex.match(email).hasMatch();
    if(!isMatch)
    {
        //作出错误提示

        showTip("邮箱地址错误",false);
    }
    else
    {
        /*
         * (QUrl url,QJsonObject json,ReqId req_id, Modules mod);
         */
        QJsonObject json;
        json["email"]=email;
        qDebug()<<gate_url_prefix<<Qt::endl;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_verifycode"),json,ReqId::ID_GET_VERIFY_CODE,Modules::REGISTERMOD);


    }

}

void RegisterDialog::showTip(QString msg,bool b_ok)
{

    if(b_ok)
    {
        ui->err_tip->setProperty("state","normal");

    }
    else
    {
        ui->err_tip->setProperty("state","err");
    }
    ui->err_tip->setText(msg);
    repolish(ui->err_tip);
}

void RegisterDialog::initHttpHandlers()
{
    _handlers[ReqId::ID_GET_VERIFY_CODE] = [this](QJsonObject obj){
        int error = obj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS)
        {
            showTip("参数错误",false);
            return;
        }
        //服务器已经接收到获取验证码命令，则提示用户注意接收验证码
        showTip("验证码已发送，请注意接收",true);
        qDebug()<<">>email is "<<obj["email"].toString()<<"\n";

    };
    _handlers[ReqId::ID_REG_USER] = [this](QJsonObject obj){
        int error = obj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS)
        {
            showTip("参数错误",false);
            return;
        }
        showTip("用户注册成功",true);
        //切换注册页面到登陆页面
        ChangeTipPage();
    };

}

void RegisterDialog::AddTipErr(TipErr te, QString tips)
{
    tip_errs_[te]=tips;
}

void RegisterDialog::DelTipErr(TipErr te)
{
    tip_errs_.remove(te);
    if(tip_errs_.empty())
    {
        ui->err_tip->clear();
        return;
    }
    showTip(tip_errs_.first(),false);
}

void RegisterDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCodes err)
{

    //判断接收的错误码
    if(err!=ErrorCodes::SUCCESS)
    {
        showTip("网络请求错误",false);
    }

    //解析字符串 res
        //将res转化为QByteArray
    QByteArray byteArray = res.toUtf8();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);

    //判断json解析是否成功
    if(jsonDoc.isNull())
    {
        showTip("json解析失败",false);
        return;
    }


    if(!jsonDoc.isObject())
    {
        showTip("json解析失败",false);
        return;
    }
    QJsonObject json = jsonDoc.object();

    //作出逻辑处理，调用对应的回调函数
    _handlers[id](json);


    return;

}






void RegisterDialog::on_sure_btn_clicked()
{


    QJsonObject json;
    json["user"] = ui->user_edit->text();
    json["email"] = ui->email_edit->text();
    json["passwd"] = ui->pass_edit->text();
    json["confirm"] = ui->confirm_edit->text();
    json["verifycode"] = ui->verify_edit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_register"),json,ReqId::ID_REG_USER,Modules::REGISTERMOD);

}


bool RegisterDialog::checkUserValid()
{
    if(ui->user_edit->text()=="")
    {
        AddTipErr(TipErr::TIP_USER_ERR,"用户名不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool RegisterDialog::checkPassValid()
{
    QString pass = ui->pass_edit->text();
    if(pass.length()<6||pass.length()>15)
    {
        AddTipErr(TipErr::TIP_PWD_ERR,"密码长度应为6~15");
        return false;
    }

    // 创建一个正则表达式对象，按照上述密码要求
    // 这个正则表达式解释：
    // ^[a-zA-Z0-9!@#$%^&*]{6,15}$ 密码长度至少6，可以是字母、数字和特定的特殊字符
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        //提示字符非法
        AddTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符"));
        return false;
    }


    DelTipErr(TIP_PWD_ERR);
    return true;
}

bool RegisterDialog::checkEmailValid()
{
    //验证邮箱的地址正则表达式
    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();

    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,tr("邮箱不能为空check"));
        return false;
    }

    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool RegisterDialog::checkVerifyValid()
{
    auto pass = ui->verify_edit->text();
    if(pass.isEmpty())
    {
        AddTipErr(TipErr::TIP_VARIFY_ERR,"验证码不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

bool RegisterDialog::checkConfirmValid()
{
    QString pass = ui->pass_edit->text();
    bool ret = checkPassValid();
    if(!ret) return ret;
    QString passConfirm = ui->confirm_edit->text();
    if(passConfirm!=pass)
    {
        AddTipErr(TipErr::TIP_CONFIRM_ERR,"确认密码与密码不一致");
        return false;
    }
    DelTipErr(TipErr::TIP_CONFIRM_ERR);
    return true;
}

void RegisterDialog::ChangeTipPage()
{
    //执行页面切换并开始计时
    countdown_timer_->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);
    countdown_timer_->start(1000);

}
//次槽函数执行后，就停止计时器，然后发出切换到登陆界面的信号
void RegisterDialog::on_return_btn_clicked()
{
    countdown_timer_->stop();
    emit sigSwitchLogin();
}


void RegisterDialog::on_cancel_btn_clicked()
{
    countdown_timer_->stop();
    emit sigSwitchLogin();
}

